
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include <semphr.h>

#include "hw_config.h"

extern void vTaskConsole(void *pvParameters);

xSemaphoreHandle xSemHwInit = NULL;

struct sHwInit {
    void (*init) (void) ; // Pointer to init
    char * path;        // path to /dev/xxx
};

static const struct sHwInit hw_init_s[] = {
    { &gpio_hw_init, "gpio" },
#if defined (COOLBIC) ||  defined (TESTING)
//    { &adc_hw_init, "voltage" },
//    { &display_hw_init, "display" },
#endif
    { &console_hw_init, "console" },
//    { &radio_hw_init, "radio" },
    { NULL, NULL}
};

void vTaskHwInit (void *pvParameters)
{
    int step;
    xSemaphoreTake( xSemHwInit, 0xffff );
    
    for (step = 0; ; step++) {
        if (hw_init_s[step].init == NULL) break;
        hw_init_s[step].init();
    }
    
    xSemaphoreGive( xSemHwInit );
    
    vTaskDelete(NULL);	
}

void vLedTask (void *pvParameters)
{
    uint8_t state = 0;
    
    vTaskDelay( 100 );
    xSemaphoreTake( xSemHwInit, 0xffff ); // Waiting to finish hw init
    xSemaphoreGive( xSemHwInit );
    
    while(1)
    {
        vTaskDelay( 100 );
        if (state == 0)
        {
            LED2_ON;
            LED1_OFF;
            state = 1;
        }
        else
        {
            LED1_ON;
            LED2_OFF;
            state = 0;
        }
    }
    vTaskDelete(NULL);	
}

int main()
{
    vSemaphoreCreateBinary( xSemHwInit );

    // Hardware initialization
    xTaskCreate( vTaskHwInit, ( signed char * ) "Init", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
    
    /* Start script interpreter */


    /* Just test - remove it */
    xTaskCreate(vLedTask,(signed char*)"LedTask", configMINIMAL_STACK_SIZE,
					NULL, tskIDLE_PRIORITY + 1, NULL);
    
    /* Optional - Create the task that handles the CLI on USART.  */
    xTaskCreate( vTaskConsole, ( signed char * ) "CLI", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL );

    
    vTaskStartScheduler();

    return 0;
}

